import axios from 'axios'
import { getToken } from './token'
import store from '@/store'

const service = axios.create({
  baseURL: 'http://localhost:8080', // process.env.BASE_API,
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => response,
  error => {
    // 服务端未登陆，客户端需要重新登陆
    if (error.response.status === 401) {
      store.dispatch('logout')
    }
    return Promise.reject(error)
  }
)

export default service
